﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Documents;

namespace System
{
    public class CsvHelper
    {
        /// <summary>
        /// 将excel导入到list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static List<T> OpenCsv<T>(string filePath) where T : class, new()
        {
            List<T> ts = new List<T>();
            if (filePath.IsNullOrWhiteSpace() || !File.Exists(filePath))
                return ts;
            StreamReader sr = null;
            FileStream fs = null;
            T t = new T();
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                sr = new StreamReader(fs);
                // 获得此模型的公共属性
                var propertys = t.GetType().GetProperties().ToList();

                //记录每次读取的一行记录
                string strLine = null;
                //记录每行记录中的各字段内容
                string[] arrayLine = null;
                //分隔符
                string[] separators = { "," };
                //判断，若是第一次，建立表头
                bool isFirst = true;

                Dictionary<int, string> keyValues = new Dictionary<int, string>();
                //逐行读取CSV文件
                while ((strLine = sr.ReadLine()) != null)
                {
                    strLine = strLine.Trim();//去除头尾空格
                    arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);//分隔字符串，返回数组
                    int dtColumns = arrayLine.Length;//列的个数

                    if (isFirst)  //建立表头
                    {
                        for (int i = 0; i < dtColumns; i++)
                        {
                            keyValues[i] = arrayLine[i];
                        }
                        isFirst = false;
                    }
                    else
                    {
                        t = new T();

                        for (int k = 0; k < dtColumns; k++)
                        {
                            object value = arrayLine[k];

                            if (!keyValues.ContainsKey(k))
                                continue;
                            var Name = keyValues[k];
                            //循环属性
                            foreach (var pi in propertys)
                            {
                                if (!pi.Name.Equals(Name))
                                    continue;
                                //获取属性类型名称
                                var s = pi.PropertyType.Name;

                                //如果非空，则赋给对象的属性
                                if (value == DBNull.Value)
                                    continue;
                                //判断属性的类型(可以自行添加)
                                switch (s)
                                {
                                    case "Int32":
                                        pi.SetValue(t, value.ToString().ToInt32(), null);
                                        break;
                                    case "Decimal":
                                        pi.SetValue(t, value.ToString().ToDecimal(), null);
                                        break;
                                    case "DateTime":
                                        pi.SetValue(t, value.ToString().ToDateTime(), null);
                                        break;
                                    case "Double":
                                        pi.SetValue(t, value.ToString().ToDouble(), null);
                                        break;
                                    case "String":
                                        pi.SetValue(t, value, null);
                                        break;
                                }
                            }
                        }
                        //对象添加到泛型集合中
                        ts.Add(t);
                    }
                }

                sr?.Close();
                fs?.Close();
                return ts;
            }
            catch (Exception ex)
            {
                sr?.Close();
                fs?.Close();
                return ts;
            }
        }

        /// <summary>
        /// 将excel导入到list
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath">文件路径</param>
        /// <param name="list">转换的Dictionary：例如 ("昵称","nickname")</param>
        /// <returns></returns>
        public static List<T> OpenCsv<T>(string filePath, Dictionary<string, string> list) where T : class, new()
        {
            List<T> ts = new List<T>();
            if (filePath.IsNullOrWhiteSpace() || !File.Exists(filePath))
                return ts;
            StreamReader sr = null;
            FileStream fs = null;
            T t = new T();
            try
            {
                fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                sr = new StreamReader(fs);
                // 获得此模型的公共属性
                var propertys = t.GetType().GetProperties().ToList();

                //记录每次读取的一行记录
                string strLine = null;
                //记录每行记录中的各字段内容
                string[] arrayLine = null;
                //分隔符
                string[] separators = { "," };
                //判断，若是第一次，建立表头
                bool isFirst = true;

                Dictionary<int, string> keyValues = new Dictionary<int, string>();
                //逐行读取CSV文件
                while ((strLine = sr.ReadLine()) != null)
                {
                    strLine = strLine.Trim();//去除头尾空格
                    arrayLine = strLine.Split(separators, StringSplitOptions.RemoveEmptyEntries);//分隔字符串，返回数组
                    int dtColumns = arrayLine.Length;//列的个数

                    if (isFirst)  //建立表头
                    {
                        for (int i = 0; i < dtColumns; i++)
                        {
                            keyValues[i] = arrayLine[i];
                        }
                        isFirst = false;
                    }
                    else
                    {
                        t = new T();

                        for (int k = 0; k < dtColumns; k++)
                        {
                            object value = arrayLine[k];

                            if (!keyValues.ContainsKey(k))
                                continue;

                            var tempKey = keyValues[k];
                            if (!list.ContainsKey(tempKey))
                                continue;
                            var Name = list[tempKey];
                            //循环属性
                            foreach (var pi in propertys)
                            {
                                if (!pi.Name.Equals(Name))
                                    continue;
                                //获取属性类型名称
                                var s = pi.PropertyType.Name;

                                //如果非空，则赋给对象的属性
                                if (value == DBNull.Value)
                                    continue;
                                //判断属性的类型(可以自行添加)
                                switch (s)
                                {
                                    case "Int32":
                                        pi.SetValue(t, value.ToString().ToInt32(), null);
                                        break;
                                    case "Decimal":
                                        pi.SetValue(t, value.ToString().ToDecimal(), null);
                                        break;
                                    case "DateTime":
                                        pi.SetValue(t, value.ToString().ToDateTime(), null);
                                        break;
                                    case "Double":
                                        pi.SetValue(t, value.ToString().ToDouble(), null);
                                        break;
                                    case "String":
                                        pi.SetValue(t, value, null);
                                        break;
                                }
                            }
                        }
                        //对象添加到泛型集合中
                        ts.Add(t);
                    }
                }

                sr?.Close();
                fs?.Close();
                return ts;
            }
            catch (Exception ex)
            {
                sr?.Close();
                fs?.Close();
                return ts;
            }
        }

    }
}
